package logic

import (
	"context"
	"errors"
	"newhouse/model/cache"
	"newhouse/model/mysql"
	"newhouse/pkg"

	"newhouse/houserpc/houserpc"
	"newhouse/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *houserpc.RegisterRequest) (*houserpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	//短信
	result, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Username).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误")
	}

	//图片
	results, err := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Result()
	if results != in.CaptchaCode {
		return nil, errors.New("图片验证码错误")
	}

	user := &mysql.User{
		Username: in.Username,
		Password: pkg.Md5(in.Password),
	}

	err = user.Register(mysql.DB)
	if err != nil {
		return nil, err
	}

	return &houserpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
